#include <myhead.h>
#include "service.h"
#include "dao.h"
#include "mypkg.h"

int user_service_reg(char* username, char* passwd, char* buf, int* buflen){
    //
    db_user_t res={0};
	int cnt=tbl_user_select(username, &res);
	if(cnt==-1){
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"ERROR","查询tbl_user表时出现错误");
        return -1;
    }

    if(cnt>0 && strcmp(username, res.username)==0){
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"FAIL","该用户已经存在");
        return -1;                                                         
    }
    
    if(tbl_user_insert(username, passwd)==-1){
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"ERROR","插入tbl_user表时出现错误");
        return -1;
    }
    //成功
	*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"OK","注册成功");
    return 0;
}

int user_service_login(char* username, char* passwd, char* ip, int port, 
		char* buf, int* buflen ){
    //校对用户名、密码
    db_user_t res={0};
	int cnt=tbl_user_select(username, &res);
	if(cnt==-1){
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"ERROR","查询tbl_user表时出现错误");
        return -1;
    }
	if(cnt==0){
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"FAIL","该用户不存在");
		return -1;
	}

    if(strcmp(username, res.username)!=0){
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"FAIL","用户名或者密码错误[1]");
        return -1;                                                         
    }
	
	if(strcmp(passwd, res.passwd) != 0){
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"FAIL","用户名或者密码错误[2]");
        return -1;                                                         
	}

	//查询用户的在线信息
	long current=time(NULL);
	ol_data_t* data=ol_link_findByName(username);
	if(data==NULL){
		//该用户之前尚未登录
		ol_link_insert(username, ip, port, current);
	}else{
		ol_link_updateByName(username, ip, port, current);
	}
	
	*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"OK","登录成功");
	return 0;
}


int user_service_heart(char* username,char* ip,int port, char* buf, int* buflen){
	//ol_link_show(onlineLink);
	//若用户名、ip一致，则更新用户在线列表
	ol_data_t* data=ol_link_findByName(username);
	if(data == NULL){
		fprintf(stderr, "服务端收到非法的心跳，用户[%s]尚未登录\n", username);
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"ERROR","非法心跳，您尚未登录！");
		return -2;
	}
	//判断用户是否在同一台机器已经登录
	if(strcmp(data->addr, ip)==0 && data->port == port){//IP和端口都相同
		data->hearttime=time(NULL);//更新最近的心跳时间
		*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"OK","正确的心跳回复");
		return 0;
	}	
	//否则什么也不做. 非登录用户的操作访问，在后续的通信中加一层登录拦截
	fprintf(stderr, "服务端收到非法的心跳，用户[%s]已经在异地[%s:%d]登录\n", username,
			data->addr, data->port);
	*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"ERROR","用户从其他地方登录了，您被挤掉了！");
	return -2;
	
}

int user_service_logout(char* username, char* buf, int* buflen){
	//从用户在线列表中删除该用户的在线信息
	ol_link_removeByName(username);

	//返回成功即可
	*buflen = pkg_pack_buf(buf, MSG_TYPE_RET, 2,"OK","退出登录成功");
	return 0;
}

